<template>
    <div class="menu">
        <div class="head">
          <slot name="head"></slot>
        </div>
        <div class="main">
        <ScrollBar :vertical="true" ref="bar">
        <ul class="menu-wrap">
          <slot></slot>
        </ul>
        </ScrollBar>
        </div>
        <div class="footer">
          <slot name="footer"></slot>
        </div>
    </div>
</template>
<script>
import ScrollBar from '@/element/scrollbar'
import Emitter from '../mixins/emitter';
export default {
  name: 'Menu',
  components: {
    ScrollBar
  },
  mixins: [ Emitter ],
  props: {
    activeName: {
      type: [String, Number]
    },
    openNames: {
          type: Array,
          default () {
              return [];
          }
    },
    width: {
          type: String,
          default: '240px'
      },
    spread: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
       currentActiveName: this.activeName
    }
  },
  methods: {
    updateActiveName() {
      this.broadcast('MenuItem', 'on-update-active-name', this.currentActiveName);
    }
  },
  watch: {
    openNames: {
      handler: function(names) {
          if (names.length) {
           this.$nextTick(() => {
             this.broadcast('submenu', 'on-open-submenu', names[0])           
           })
          };    
        },
        immediate: true
    },
    activeName (val) {
        this.currentActiveName = val;
    },
    currentActiveName () {
        this.updateActiveName();
    },
    spread: {
     handler: function(now,old) {
      // this.broadcast('submenu', 'on-update-spread', this.spread);
      this.$nextTick(() => {
        this.updateActiveName();
      })
      setTimeout(() => {
           this.$refs.bar.resize(); 
      },300)
     },
     immediate: true
    }
  },
  mounted() {
     this.updateActiveName();
     this.$on('on-menu-item-select', ({name, el}) => {
                this.currentActiveName = name;
                this.$emit('on-select', name);
                // this.broadcast('submenu', 'on-active-change', el);
     });
     this.$on('on-submenu-select', name => {
        this.$emit('on-open-change', name)
        this.broadcast('submenu', 'on-update-active-submenu', name);
        setTimeout(() => {
           this.$refs.bar.resize(); 
        },200)
     })
     this.$on('on-init-active-name', () => {
       this.updateActiveName();
     })
     this.$on('on-active-change', el => {
        this.broadcast('submenu', 'on-active-change', el);
     })
  }
}
</script>
<style lang="less">
  @import './style.less';
</style>